import React, {Component} from 'react'
import {
    StyleSheet,
    View,
    Text,
    Button
} from 'react-native'
import {createAppContainer} from 'react-navigation'
import {createMaterialTopTabNavigator} from 'react-navigation-tabs'
import axios from 'axios'
import DataStore from '../Http/AsDemo'
import AsyncStorage from '@react-native-community/async-storage'


class HomePage extends Component{
    constructor(props){
        super(props)
        this.names = ['推荐', '视频', '热点', '社会', '娱乐', '军事', '科技', '汽车', '房产', '家居', '体育', '财经']
        // this.names = ['HTML5', 'CSS3', 'JavaScript', 'React', 'Vue', 'ThreeJS']
    }
    _getTabs(){
        let obj = {}
        this.names.forEach(item => {
            obj[item] = {
                screen: (props) => {
                    return <NewsItem {...props} onGoTo={() => {
                        this.props.navigation.navigate('DetailPage')
                    }} content={item}></NewsItem>
                }
            }
        })
        return obj
    }
    render(){
        const TopTabs = createAppContainer(createMaterialTopTabNavigator(this._getTabs(), {
            lazy: true,
            tabBarOptions: {
                scrollEnabled: true,
                tabStyle: {
                    width: 70
                }
            }
        }))
        return <TopTabs></TopTabs>
    }
}

class NewsItem extends Component{
    constructor(props){
        super(props)
    }
    componentDidMount() {
        this.testFetch()
        // this.testDataStore()
    }
    testDataStore(){
        const _data_store = new DataStore()
        _data_store.fetchData('https://api.github.com/search/repositories?q=NodeJS').then(res => {
            console.log(res)
        }).catch(err => {
            console.log(err)
        })
    }
    testFetch(){
        let url = "https://api.github.com/search/repositories?q=NodeJS"
        // fetch(url)
        // .then(response => {
        //     console.log(response)
        //     if (response.ok) {
        //         return response.json()
        //         // return response.text()
        //     }
        //     throw new Error("请求异常")
        // })
        // .then(responseText => {
        //     console.log(responseText)
        // })
        // .catch(err => {
        //     console.log(err)
        // })
        //也可以用axios
        axios(url).then(res => {
            console.log(res)
            alert(JSON.stringify(res.data.content))
        })
    }
    render(){
        return (
            <View>
                <Text>{this.props.content}</Text>
                <Button title="查看详情" onPress={() => {
                    this.props.onGoTo()
                    //因为NewsItem组件没有注册路由所以不能直接跳转详情页
                }}></Button>
                <Button title="清除数据库" onPress={() => {
                    AsyncStorage.clear()
                }}></Button>
            </View>
        )
    }
}

const style = StyleSheet.create({
    
})

export default HomePage